package com.example.interviewdemo.reentrantLock;

/**
 * @program my-project-model
 * @description:
 * @author: lee
 * @create: 2023/01/04 09:31
 */
public class MyReentrantLock {

    private boolean isLocked = false;
    private String currentThreadName = "";


    public boolean isLocked() {
        return isLocked;
    }

    public synchronized void lock() throws InterruptedException {
        //第一次上锁
        if (currentThreadName.equals("")) {
            System.out.println("第一次上锁" + Thread.currentThread().getName());
            isLocked = true;
            currentThreadName = Thread.currentThread().getName();
        } else if (Thread.currentThread().getName().equals(currentThreadName)) {
            System.out.println("当前线程是之前加锁的线程" + Thread.currentThread().getName());
        } else {
            //其他线程上锁，需要等待
            System.out.println("当前锁被其他线程占用，请等待" + Thread.currentThread().getName());
            wait();
        }
    }

    public synchronized void unLock() {
        //锁只能被当前占有锁的线程释放
        if (Thread.currentThread().getName().equals(currentThreadName)) {
            System.out.println("锁被释放");
            isLocked = false;
            notify();
        } else {
            System.out.println("当前线程没有占有锁，无法释放锁");
        }
    }

}
